import cv2
import numpy as np
import matplotlib.pyplot as plt # plt 用于显示图片
import matplotlib.image as mpimg # mpimg 用于读取图片
import os


# 显示图片
def cv_show(name,img):
    cv2.imshow(name,img)
    cv2.waitKey()
    cv2.destroyAllWindows()

# plt显示彩色图片
def plt_show0(img):
    b,g,r = cv2.split(img)
    img = cv2.merge([r, g, b])
    plt.imshow(img)
    plt.show()
    
# plt显示灰度图片
def plt_show1(img):
    plt.imshow(img,cmap='gray')
    plt.show()

# 图像去噪灰度处理
def gray_guss(image):
    image = cv2.GaussianBlur(image, (3, 3), 0)
    gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    return gray_image


img = cv2.imread("rawImg888.png",cv2.IMREAD_COLOR)
qzimg = cv2.GaussianBlur(img,(5,5),0.8,0.8)#高斯核大小 中心点为中心3 * 3的邻域做操作
gray_imag = cv2.cvtColor(qzimg,cv2.COLOR_RGB2GRAY)
#cv2.imshow("test",gray_imag
Sobel_x = cv2.Sobel(gray_imag,cv2.CV_64F,1,0)
absX = cv2.convertScaleAbs(Sobel_x)
image = absX
ret,image = cv2.threshold(image, 0, 255,cv2.THRESH_OTSU)
kernelX = cv2.getStructuringElement(cv2.MORPH_RECT, (17, 5))
image = cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernelX, iterations=3)
kernelX = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 1))
kernelY = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 19))
image = cv2.dilate(image, kernelX)
image = cv2.erode(image, kernelX)
# 腐蚀膨胀
image = cv2.erode(image, kernelY)
image = cv2.dilate(image, kernelY)
image = cv2.medianBlur(image, 15)
cv2.RETR_EXTERNAL
# cv2.CHAIN_APPROX_SIMPLE压缩水平方向、垂直方向、对角线方向的元素，只保留该方向的终点坐标
contours, hierarchy = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
image_copy = img.copy()
cv2.drawContours(image_copy, contours, -1, (0, 255, 0), 2)
for item in contours:
    rect = cv2.boundingRect(item)
    x = rect[0]
    y = rect[1]
    weight = rect[2]
    height = rect[3]
    if (weight > (height * 3)) and (weight < (height * 4)):
        image = img[y:y + height, x:x + weight]

#cv2.imwrite("rawImg5.png",image)
#对提取出来的车牌进行字符分割
#对车牌进行高斯去噪
qzcp = cv2.GaussianBlur(image,(3,3),0)
#灰度处理
gray_cpimg = cv2.cvtColor(qzcp,cv2.COLOR_RGB2GRAY)
#自适应阈值处理
ret,cpimages = cv2.threshold(gray_cpimg,0,255,cv2.THRESH_OTSU)
#闭运算
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))
image1 = cv2.dilate(cpimages, kernel)
#对其再进行轮廓检测
contours, hierarchy = cv2.findContours(image1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)


rawImg = cv2.imread("rawImg888.png",cv2.IMREAD_COLOR)
image_copy = rawImg.copy()

rt=cv2.drawContours(image_copy, contours, -1, (0, 0, 255), 1)
#plt_show0(rt)
#cv2.imwrite("Img5.png",contours)
#筛选出各个字符的轮廓，对其进行分割处理
	#把每个字符的位置存到了words数组里
words = []
word_images = []
for item in contours:
    # 用一个最小的矩形把找到的形状包起来
    word = []
    rect = cv2.boundingRect(item)
    x = rect[0]
    y = rect[1]
    weight = rect[2]
    height = rect[3]
    word.append(x)
    word.append(y)
    word.append(weight)
    word.append(height)
    words.append(word)
#paixu
words = sorted(words, key=lambda s: s[0], reverse=False)
#print(words)
	#根据字符位置进行字符的分割处理
i = 0
for word in words:
    if (word[3] > (word[2] * 1.8)) and (word[3] < (word[2] * 3.5)):
        i += 1
        split_image = rawImg[word[1]:word[1] + word[3], word[0]:word[0] + word[2]]
        #plt_show0(split_image)
        word_images.append(split_image)
#print(words)
for i, j in enumerate(word_images):
    plt.subplot(1, 7, i + 1)
    plt.imshow(word_images[i], cmap='gray')
    #plt_show0(word_images[i])
plt.show()	


